﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xpus.YouYTube.Data;

namespace Xpus.YouYTube.Utility
{
	/// <summary>
	/// 提供有关IP地址的操作。
	/// </summary>
	public static class TIpUtility
	{
		/// <summary>
		/// 屏蔽一个IP地址。
		/// </summary>
		/// <param name="ip">待屏蔽的IP地址。</param>
		/// <param name="refreshLastVisitTime">是否将其LastVisitTime刷新到当前时间。</param>
		public static void Block(string ip, bool refreshLastVisitTime)
		{
			using (TDataContext db = new TDataContext())
			{
				TIpBlock tib = db.TIpBlocks.FirstOrDefault(b => b.IpAddress == ip);

				if (tib == null)
				{
					tib = new TIpBlock() { IpAddress = ip, LastVisitTime = DateTime.Now };
					db.TIpBlocks.InsertOnSubmit(tib);
					db.SubmitChanges();
				}

				if (refreshLastVisitTime)
				{
					tib.LastVisitTime = DateTime.Now;
					db.SubmitChanges();
				}
			}
		}

		/// <summary>
		/// 解除对一个IP地址进行的屏蔽。
		/// </summary>
		/// <param name="ip">待解除屏蔽的IP地址。</param>
		public static void UnBlock(string ip)
		{
			using (TDataContext db = new TDataContext())
			{
				TIpBlock tib = db.TIpBlocks.FirstOrDefault(b => b.IpAddress == ip);

				if (tib != null)
				{
					db.TIpBlocks.DeleteOnSubmit(tib);
					db.SubmitChanges();
				}
			}
		}

		/// <summary>
		/// 检查一个IP地址是否已被屏蔽。
		/// </summary>
		/// <param name="ip">待检查的IP地址。</param>
		/// <param name="refreshLastVisitTime">是否将其LastVisitTime刷新到当前时间。</param>
		/// <returns>如果IP地址已被屏蔽，返回true；否则返回false。</returns>
		public static bool IsIpBlocked(string ip, bool refreshLastVisitTime)
		{
			using (TDataContext db = new TDataContext())
			{
				TIpBlock tib = db.TIpBlocks.FirstOrDefault(b => b.IpAddress == ip);

				if (tib == null)
					return false;

				if (refreshLastVisitTime)
				{
					tib.LastVisitTime = DateTime.Now;
					db.SubmitChanges();
				}

				return true;
			}
		}

		/// <summary>
		/// 对IP地址进行混淆，以备显示给管理员。目前是将最后一位替换为“*”。
		/// </summary>
		/// <param name="ip">待混淆的IP地址。</param>
		/// <returns></returns>
		public static string GetDisplayIp(string ip)
		{
			return TRegexUtility.IP.Replace(ip, "$1.$2.$3.*");
		}
	}
}
